﻿create PROCEDURE Sync.SP_RolesPermissions_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @RolesPermissions_Temp TABLE 
		(
			PermissionID UniqueIdentifier,
	RoleID UniqueIdentifier,
			
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @RolesPermissions_Temp 
	   SELECT	Tbl.Col.value('PermissionID[1]','uniqueidentifier') PermissionID,
Tbl.Col.value('RoleID[1]','uniqueidentifier') RoleID,
                
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/RolesPermissions') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[RolesPermissions] ([PermissionID],[RoleID])
	SELECT t.[PermissionID],t.[RoleID]
	FROM  @RolesPermissions_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.RolesPermissions_Tracking s
        WHERE t.PermissionID = s.PermissionID AND t.RoleID = s.RoleID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
    -----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[RolesPermissions]
    FROM @RolesPermissions_Temp t JOIN [dbo].[RolesPermissions] s
    ON t.PermissionID = s.PermissionID AND t.RoleID = s.RoleID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END





